package cn.jesin.css.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.jesin.css.entity.Creation;
import cn.jesin.css.entity.User;
import cn.jesin.css.entity.UserConnection;
import cn.jesin.css.mapper.CreationMapper;
import cn.jesin.css.mapper.UserConnectionMapper;
import cn.jesin.css.mapper.UserMapper;
import cn.jesin.css.service.CreationService;
import cn.jesin.css.utils.OSSFileUtil;
import cn.jesin.css.vo.CreationInfo;
import cn.jesin.css.vo.Page;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 谷汉斌
 * @description
 * @createTime 2024/8/21 上午10:02
 */
@Service
public class CreationServiceImpl implements CreationService {

    @Resource
    private CreationMapper creationMapper;

    @Autowired
    private OSSFileUtil ossFileUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserConnectionMapper userConnectionMapper;

    /**
     * 添加作品
     *
     * @param creation 作品信息
     * @return 是否添加成功
     */
    @Override
    public boolean addCreation(Creation creation) {
        if (StrUtil.isNotBlank(creation.getTitle()) && StrUtil.isNotBlank(creation.getAuthorId())
                && StrUtil.isNotBlank(creation.getType()) && StrUtil.isNotBlank(creation.getTag())) {
            creation.setLikeCount(0);
            creation.setFavoriteCount(0);
            creation.setUnlikeCount(0);
            creation.setViewCount(0);
            creation.setCommentCount(0);
            Date updateTime = new Date(System.currentTimeMillis());
            Date createTime = new Date(System.currentTimeMillis());
            creation.setUpdateTime(updateTime);
            creation.setCreateTime(createTime);
            return creationMapper.insertCreation(creation) > 0;
        }
        return false;
    }

    /**
     * 删除作品
     *
     * @param id 作品id
     * @return 是否删除成功
     */
    @Override
    public boolean deleteCreation(Integer id) {
        return creationMapper.deleteCreation(id) > 0;
    }

    /**
     * 分页返回作品列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @param isFinish 是否完结
     * @param type     类型
     * @param keyword  关键词
     * @return 作品列表
     */
    @Override
    public Page<CreationInfo> getCreationList(Integer pageNum, Integer pageSize, Integer isFinish, String type, String keyword) {
        // 页码小于等于1，则默认为1
        if (pageNum <= 1) {
            pageNum = 1;
        }
        //开始页码-1*每页显示的条数
        pageNum = (pageNum - 1) * pageSize;
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("isFinish", isFinish);
        map.put("type", type);
        map.put("keyword", keyword);
        List<Creation> creationList = creationMapper.selectCreationList(map);
        List<CreationInfo> creationInfoList = new ArrayList<>();
        // 设置封面地址和作品信息
        if (!creationList.isEmpty()) {
            for (Creation creation : creationList) {
                if (StrUtil.isNotBlank(creation.getCover())) {
                    String url = ossFileUtil.getUrl(creation.getCover());
                    if (StrUtil.isNotBlank(url)) {
                        creation.setCoverUrl(url);
                    }
                }
                //设置作品信息
                creationInfoList.add(new CreationInfo(creation));
            }
        }
        //判断当前用户是点赞或收藏了这些作品
        //获取当前用户登录的信息
        //获取当前登录的信息
        String username = null;
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String info = principal.getUsername();
        //提取登录的唯一凭证和类型
        String loginKey = info.split(":")[0];
        String loginType = info.split(":")[1];
        if (StrUtil.isNotBlank(loginKey)) {
            User user = userMapper.selectUserByKey(Map.of(loginType, loginKey));
            username = user.getUsername();
            UserConnection userConnection = userConnectionMapper.getUserConnection(username);
            if (!creationInfoList.isEmpty() && userConnection != null) {
                for (CreationInfo creationInfo : creationInfoList) {
                    //判断当前用户是否点赞了该作品
                    if (StrUtil.isNotBlank(userConnection.getCreationLikeMap().get(creationInfo.getId()))) {
                        creationInfo.setLike(true);
                    }
                    //判断当前用户是否收藏了该作品
                    if (StrUtil.isNotBlank(userConnection.getCreationFavoriteMap().get(creationInfo.getId()))) {
                        creationInfo.setFavorite(true);
                    }
                }
            }
        }

        Integer total = creationMapper.selectTotal(map);
        Page<CreationInfo> page = new Page<>();
        page.setData(creationInfoList);
        page.setPageNum(pageNum + 1);
        page.setPageSize(pageSize);
        page.setTotal(total);
        return page;
    }

    /**
     * 更新作品
     *
     * @param creation 作品信息
     * @return 是否更新成功
     */
    @Override
    public boolean updateCreation(Creation creation) {
        if (StrUtil.isNotBlank(creation.getTitle()) && StrUtil.isNotBlank(creation.getAuthorId())
                && StrUtil.isNotBlank(creation.getType()) && StrUtil.isNotBlank(creation.getTag())
                && creation.getLikeCount() >= 0 && creation.getFavoriteCount() >= 0 && creation.getUnlikeCount() >= 0
                && creation.getCreateTime() != null && creation.getViewCount() >= 0 && creation.getCommentCount() >= 0) {
            //
            return creationMapper.updateCreation(creation) > 0;
        }
        return false;
    }

    /**
     * 操作作品
     *
     * @param id          作品id
     * @param operate     操作
     * @param operateType 操作类型
     * @param creation    作品信息
     * @return 是否操作成功
     */
    @Override
    public boolean operate(Integer id, String operate, String operateType,Creation creation) {
        if (StrUtil.isBlank(operateType) || null == id || StrUtil.isBlank(operate)|| null == creation) {
            return false;
        }
        //获取当前用户登录的信息
        String username = null;
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String info = principal.getUsername();
        //提取登录的唯一凭证和类型
        String loginKey = info.split(":")[0];
        String loginType = info.split(":")[1];
        if (StrUtil.isNotBlank(loginKey)) {
            User user = userMapper.selectUserByKey(Map.of(loginType, loginKey));
            //获取当前用户的联系信息
            UserConnection userConnection = userConnectionMapper.getUserConnection(user.getUsername());
            if (userConnection != null) {
                //如果用户操的是点赞
                if ("like".equals(operate)) {
                    Map<Integer, String> creationLikeMap = userConnection.getCreationLikeMap();
                    if ("add".equals(operateType)) {
                        //添加点赞
                        creationLikeMap.put(id, String.valueOf(id));
                        userConnection.setCreationLikeMap(creationLikeMap);
                        //更新作品的点赞数
                        creationMapper.updateCreation(creation);
                        return userConnectionMapper.updateUserConnection(userConnection) > 0;
                    } else if ("cancel".equals(operateType)) {
                        //删除点赞
                        creationLikeMap.remove(id);
                        userConnection.setCreationLikeMap(creationLikeMap);
                        //更新作品的点赞数
                        creationMapper.updateCreation(creation);
                        return userConnectionMapper.updateUserConnection(userConnection) > 0;
                    }
                } else if ("favorite".equals(operate)) {
                    Map<Integer, String> creationFavoriteMap = userConnection.getCreationFavoriteMap();
                    if ("add".equals(operateType)) {
                        //添加收藏
                        creationFavoriteMap.put(id, String.valueOf(id));
                        userConnection.setCreationFavoriteMap(creationFavoriteMap);
                        //更新作品的收藏数
                        creationMapper.updateCreation(creation);
                        return userConnectionMapper.updateUserConnection(userConnection) > 0;
                    } else if ("cancel".equals(operateType)) {
                        //删除收藏
                        creationFavoriteMap.remove(id);
                        userConnection.setCreationFavoriteMap(creationFavoriteMap);
                        //更新作品的收藏数
                        creationMapper.updateCreation(creation);
                        return userConnectionMapper.updateUserConnection(userConnection) > 0;
                    }
                }
            }else if ("add".equals(operateType)){
                //如果是点赞
                if ("like".equals(operate)) {
                    //添加点赞
                    Map<Integer, String> creationLikeMap = new HashMap<>();
                    creationLikeMap.put(id, String.valueOf(id));
                     userConnection = new UserConnection();
                     userConnection.setUsername(user.getUsername());
                     userConnection.setCreationLikeMap(creationLikeMap);
                     //更新作品的点赞数
                     creationMapper.updateCreation(creation);
                     return userConnectionMapper.addUserConnection(userConnection) > 0;
                 //如果是收藏
                } else if ("favorite".equals(operate)) {
                    //添加收藏
                    Map<Integer, String> creationFavoriteMap =new HashMap<>();
                    creationFavoriteMap.put(id, String.valueOf(id));
                    userConnection = new UserConnection();
                    userConnection.setUsername(user.getUsername());
                    userConnection.setCreationFavoriteMap(creationFavoriteMap);
                    //更新作品的收藏数
                    creationMapper.updateCreation(creation);
                    return userConnectionMapper.addUserConnection(userConnection) > 0;
                }
            }
        }
        return false;
    }
}
